package com.bee.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.bee.base.BaseResponse;
import com.bee.member.feign.MemberRegisterServiceFeign;
import com.bee.member.input.dto.UserInpDTO;
import com.bee.member.vo.RegisterVo;
import com.bee.web.base.BaseWebController;
import com.bee.web.bean.MeiteBeanUtils;
import com.bee.web.utils.CookieUtils;
import com.bee.web.utils.RandomValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class RegisterController extends BaseWebController {
	private static final String MB_REGISTER_FTL = "member/register";

	/**
	 * 跳转到登陆页面页面
	 */
	private static final String MB_LOGIN_FTL = "member/login";
	@Autowired
	private MemberRegisterServiceFeign memberRegisterServiceFeign;


	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@GetMapping("/register")
	public String getRegister() {
		return MB_REGISTER_FTL;
	}

	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@PostMapping("/register")
	public String postRegister(@ModelAttribute("registerVo") @Validated RegisterVo registerVo,
							   BindingResult bindingResult, HttpSession httpSession, Model model) {
		//1.参数验证
		if(bindingResult.hasErrors()){
			String errMsg = bindingResult.getFieldError().getDefaultMessage();
			setErrorMsg(model, errMsg);
			return MB_REGISTER_FTL;
		}
		//2.图形验证码
		if(!RandomValidateCodeUtil.checkVerify(registerVo.getGraphicCode(),httpSession)){
			setErrorMsg(model, "验证码不正确");
			return MB_REGISTER_FTL;
		};
		//3.注册
		UserInpDTO userInpDTO = MeiteBeanUtils.voToDto(registerVo, UserInpDTO.class);
		BaseResponse<JSONObject> result = memberRegisterServiceFeign.register(userInpDTO, registerVo.getRegistCode());
		if(!isSuccess(result)){
			setErrorMsg(model, result.getMsg());
			return MB_REGISTER_FTL;
		}
		// 4.跳转到登陆页面
		return MB_LOGIN_FTL;
	}

}
